<?php
namespace Liaiyong\Light\Data;

use Liaiyong\Light\Base\Component;
use Liaiyong\Light\Core\Error;
use Liaiyong\Light\Data\Data;

class DataResponse extends Data {
    protected $rsp = 1;
    protected $api = '';
    protected $code = 0;
    protected $data = '';
    public function rules() {
        return array(
            'rsp' => array(Component::TYPE_ENUM, array(0, 1)),
            'api' => Component::TYPE_STRING,
            'code' => array(Component::TYPE_FORMAT, array('type' => 'code')),
            'data' => array(Component::TYPE_FORMAT, array('type' => 'data'))
        );
    }
    public function format($val, $key, $option = array()) {
        $ret = '';
        switch ($key) {
            case 'code':
                if(is_numeric($val)) {
                    $ret = intval($val);
                } else if($val instanceof Error) {
                    $this->rsp = 0;
                    //$this->code = 0;
                    $ret = $val->getCode();
                    $this->data = $val->getMessage();
                }
                break;
            case 'data':
                if(is_scalar($val) && !is_null($val)) {
                    $ret = $val;
                } else if(is_array($val)){
                    $ret = $val;
                } else if($val instanceof Data){
                    $ret = $val;
                } else if($val instanceof Error) {
                    $this->rsp = 0;
                    $ret = $val->getMessage();
                    $this->code = $val->getCode();
                }
                break;
            default:
                break;
        }
        return $ret;
    }
}
// PHP END